package com.jz.community.commview.view;

import android.content.Context;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jz.community.commview.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Target
 * 广告图片自动轮播控件</br>
 */

public class AdvImageCycleView<T> extends LinearLayout {
    /**
     * 上下文
     */
    private Context mContext;
    /**
     * 图片轮播视图
     */
    private VerticalScrollViewPager mAdvPager = null;
    /**
     * 滚动图片视图适配
     */
    private ImageCycleAdapter mAdvAdapter;
    /**
     * 图片轮播指示器控件
     */
    private ViewGroup mGroup;

    /**
     * 图片轮播指示个图
     */
    private ImageView mImageView = null;

    /**
     * 滚动图片指示视图列表
     */
    private ImageView[] mImageViews = null;

    /**
     * 图片滚动当前图片下标
     */
    private int mImageIndex = 0;

    /**
     * 手机密度
     */
    private float mScale;
    private boolean isStop;

    //是否展示标题
    private boolean isShowTitle = false;

    private TextView adv_title;

    private List<T> imageUrlList;

    private ImageCycleTextListener mTextListener;

    /**
     * @param context
     */
    public AdvImageCycleView(Context context) {
        super(context);
    }

    public ImageCycleTextListener getmTextListener() {
        return mTextListener;
    }

    public void setmTextListener(ImageCycleTextListener mTextListener) {
        this.mTextListener = mTextListener;
    }

    /**
     * @param context
     * @param attrs
     */
    public AdvImageCycleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        imageUrlList = new ArrayList<>();
        mScale = context.getResources().getDisplayMetrics().density;
        LayoutInflater.from(context).inflate(R.layout.recommened_cycle_view, this);
        mAdvPager = findViewById(R.id.adv_pager);
        adv_title = findViewById(R.id.adv_title);
        mAdvPager.addOnPageChangeListener(new GuidePageChangeListener());
        startImageTimerTask();
        mAdvPager.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        // 开始图片滚动
                        startImageTimerTask();
                        break;
                    default:
                        // 停止图片滚动
                        stopImageTimerTask();
                        break;
                }
                return false;
            }
        });
        // 滚动图片右下指示器视
        mGroup = (ViewGroup) findViewById(R.id.viewGroup);

        setPageMargin();

    }

    /**
     * 每个页卡的间距
     */
    public void setPageMargin(){
        mAdvPager.setPageMargin(getResources().getDimensionPixelOffset(R.dimen.ui_5_dip));//设置viewpager每个页卡的间距，与gallery的spacing属性类似
    }

    /**
     * 装填图片数据
     *
     * @param imageUrlList
     * @param imageCycleViewListener
     */
    public void setImageResources(List<T> imageUrlList, ImageCycleViewListener imageCycleViewListener) {
        // 清除
        mGroup.removeAllViews();
        this.imageUrlList.addAll(imageUrlList);
        if (isShowTitle) {
            if (mTextListener != null) {
                mTextListener.initTitleText(imageUrlList.get(0), adv_title);
            }
        }
        // 图片轮播数量
        final int imageCount = imageUrlList.size();
        mImageViews = new ImageView[imageCount];
        if (imageCount > 1) {
            for (int i = 0; i < imageCount; i++) {
                mImageView = new ImageView(mContext);
                int imageParams = (int) (mScale * 5 + 0.5f);// XP与DP转换，适应应不同分辨率
                int imagePadding = (int) (mScale * 10 + 0.5f);
                LayoutParams params = new LayoutParams(imageParams, imageParams);
                params.leftMargin = 10;
                mImageView.setLayoutParams(params);
                mImageView.setPadding(imagePadding, imagePadding, imagePadding, imagePadding);

                mImageViews[i] = mImageView;
                if (i == 0) {
                    mImageViews[i].setBackgroundResource(R.mipmap.comm_page_indicator_foc);
                } else {
                    mImageViews[i].setBackgroundResource(R.mipmap.comm_page_indicator_nor);
                }
                mGroup.addView(mImageViews[i]);
            }
        }
        mAdvAdapter = new ImageCycleAdapter(mContext, imageUrlList, imageCycleViewListener);
        mAdvPager.setAdapter(mAdvAdapter);
        //当图片大于1张时 才启动 轮播
        if (imageCount > 1) {
            startImageTimerTask();
        }
    }

    /**
     * 图片轮播(手动控制自动轮播与否，便于资源控件）
     */
    public void startImageCycle() {
        startImageTimerTask();
    }

    /**
     * 暂停轮播—用于节省资源
     */
    public void pushImageCycle() {
        stopImageTimerTask();
    }

    /**
     * 图片滚动任务
     */
    private void startImageTimerTask() {
        stopImageTimerTask();
        // 图片滚动5s
        mHandler.postDelayed(mImageTimerTask, 5000);
    }

    /**
     * 停止图片滚动任务
     */
    private void stopImageTimerTask() {
        isStop = true;
        mHandler.removeCallbacks(mImageTimerTask);
    }

    public void setShowTitle(boolean showTitle) {
        isShowTitle = showTitle;
    }

    private Handler mHandler = new Handler();

    /**
     * 图片自动轮播Task
     */
    private Runnable mImageTimerTask = new Runnable() {
        @Override
        public void run() {
            if (mImageViews != null) {
                mAdvPager.setCurrentItem(mAdvPager.getCurrentItem() + 1);
                //mAdvPager.getCurrentItem() == 1 防止第一次滚动卡顿
                if (!isStop || mAdvPager.getCurrentItem() == 1) {  //if  isStop=true   //当你退出后 要把这个给停下来 不然 这个一直存在 就一直在后台循环
                    mHandler.postDelayed(mImageTimerTask, 5000);
                }

            }
        }
    };

    /**
     * 轮播图片监听
     *
     * @author fanguangjun
     */
    private final class GuidePageChangeListener implements OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int state) {
            if (state == ViewPager.SCROLL_STATE_IDLE) {
                startImageTimerTask();
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageSelected(int index) {
            index = index % mImageViews.length;
            // 设置当前显示的图片
            mImageIndex = index;
            // 设置图片滚动指示器背
            mImageViews[index].setBackgroundResource(R.mipmap.comm_page_indicator_foc);
            for (int i = 0; i < mImageViews.length; i++) {
                if (index != i) {
                    mImageViews[i].setBackgroundResource(R.mipmap.comm_page_indicator_nor);
                }
            }
            //如果图片上不带文字，需要自己添加，将NisShowName设置为ture
            if (isShowTitle) {
                if (mTextListener != null) {
                    mTextListener.displayText(imageUrlList.get(index), adv_title);
                }
            }
        }
    }

    private class ImageCycleAdapter<T> extends PagerAdapter {

        /**
         * 图片视图缓存列表
         */
        private ArrayList<ImageView> mImageViewCacheList;

        /**
         * 图片资源列表
         */
        private List<T> mAdList = new ArrayList<>();

        /**
         * 图片点击监听
         */
        private ImageCycleViewListener mImageCycleViewListener;

        private Context mContext;

        public ImageCycleAdapter(Context context, List<T> adList, ImageCycleViewListener imageCycleViewListener) {
            this.mContext = context;
            this.mAdList = adList;
            mImageCycleViewListener = imageCycleViewListener;
            mImageViewCacheList = new ArrayList<ImageView>();
        }

        @Override
        public int getCount() {

            if (mAdList.size() == 0) {
                return 0;
            }

            if (mAdList.size() == 1) {
                return 1;
            }
            return Integer.MAX_VALUE;
        }


        @Override
        public boolean isViewFromObject(View view, Object obj) {
            return view == obj;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            T imageUrl = mAdList.get(position % mAdList.size());
            ImageView imageView = null;
            if (mImageViewCacheList.isEmpty()) {
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            } else {
                imageView = mImageViewCacheList.remove(0);
            }
            // 设置图片点击监听
            imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mImageCycleViewListener.onImageClick(position % mAdList.size(), v);
                }
            });
            //imageView.setTag(imageUrl);
            container.addView(imageView);
            mImageCycleViewListener.displayImage(imageUrl, imageView,position % mAdList.size());
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ImageView view = (ImageView) object;
            mAdvPager.removeView(view);
            mImageViewCacheList.add(view);

        }

    }

    /**
     * 轮播控件的监听事件
     *
     * @author fanguangjun
     */
    public interface ImageCycleViewListener {
        /**
         * 加载图片资源
         *
         * @param t
         * @param imageView
         */
        <T> void displayImage(T t, ImageView imageView,int position);

        /**
         * 单击图片事件
         *
         * @param position
         * @param imageView
         */
        void onImageClick(int position, View imageView);
    }

    //轮播设置标题的方法
    public interface ImageCycleTextListener {
        /**
         * 处理设置相关标题
         *
         * @param t
         * @param textView
         * @param <T>
         */
        <T> void displayText(T t, TextView textView);

        /**
         * 初始化第一次显示的Title
         *
         * @param t
         * @param textView
         * @param <T>
         */
        <T> void initTitleText(T t, TextView textView);
    }

}
